local net = require("framework.cc.net.init")
local message = require "msghandle"
local proto = require "proto"
local Timer = require("utils.Timer")

require "pack"

local event = {}
message.bind({}, event)

-- local sprotoPath = cc.FileUtils:getInstance():fullPathForFilename("proto.c2s.sproto")
-- message.register(string.sub(sprotoPath,1,string.len(sprotoPath)-11))
message.register(proto)
local MainScene = class("MainScene", function()
    return display.newScene("MainScene")
end)

local userid
local socketData = {}

function MainScene:ctor(args)
        display.newColorLayer(cc.c4b(255,255,255,255)):addTo(self)

        userid=args
        cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
        :setButtonSize(100, 40)
        :setButtonLabel(cc.ui.UILabel.new({text = "退出"}))
        :onButtonPressed(function(event)
            event.target:setScale(1.1)
        end)
        :onButtonRelease(function(event)
            event.target:setScale(1.0)
        end)
        :onButtonClicked(function()
            app:enterScene("LoginScene", {}, "fade", 0.6, display.COLOR_WHITE)
            -- display.replaceScene(require("scenes.LoginScene").new(), "fade", 0.6, display.COLOR_WHITE)
        end)
        :pos(display.width-100/2-20, display.height-40/2-20)
        :addTo(self)

        self:connectGate()
        MainScene._self = self

        cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
        :setButtonSize(100, 40)
        :setButtonLabel(cc.ui.UILabel.new({text = "创建"}))
        :onButtonPressed(function(event)
            event.target:setScale(1.1)
        end)
        :onButtonRelease(function(event)
            event.target:setScale(1.0)
        end)
        :onButtonClicked(function()
            MainScene._self.createView=app:createView("CreateRoomView",function(name)
              message.request("createroom",{name=name,pass="123456"})
            end)
            :pos(0,0)
            :addTo(MainScene._self)

        end)
        :pos(100, display.height-40/2-20)
        :addTo(self)



end

function MainScene:onEnter()
    display.addSpriteFrames("game.plist", "game.png")
end

function MainScene:onExit()
     self:disconnectGate()
end

local scnet = {}

local index = 1
local socketMsg

function event:heartbeat(checkFlag)
    -- print("收到心跳")
    if not checkFlag then
         message.request "ping"
    end
    if MainScene._self.recv == MainScene._self.heartbeat then
        print("掉线了---------------------------------")
        MainScene._self:showReConnectTip()
     else 
        MainScene._self.recv=0
        MainScene._self.heartbeat=0
        -- Timer:runOnceTime(event:heartbeat,30,true)
    end
end

function event:onnewroom()
    -- print("有人创建房间了")
    message.request("roomlist",{page=1})
end

function event:handshake(req, resp)
    message.request("roomlist",{page=1})
    message.request("roominfo")
end

function event:roomlist(_, resp)
    if resp.ok then 
        MainScene._self:roomList(resp.room)
    end
end

function event:roominfo(_,resp)
    if resp.ok == 1 then
        --游戏状态获取成功
        --初始化游戏中各个状态
        if not MainScene._self.tableview then
            MainScene._self.roomid = resp.room.id
            MainScene._self.tableview=app:createView("TableView",socketData,{userid=userid,user=resp.user,roomid= MainScene._self.roomid})
            :pos(0,0)
            :addTo(MainScene._self)
        end
       --TODO room 1: *roominfo，card 2: string，users
        MainScene._self.tableview:roominfo(resp)
    elseif resp.ok == 2  then
        --游戏已加入，未开始
         if not MainScene._self.tableview then
            MainScene._self.roomid = resp.room.id
            MainScene._self.tableview=app:createView("TableView",socketData,{userid=userid,user=resp.user,roomid= MainScene._self.roomid})
            :pos(0,0)
            :addTo(MainScene._self)
        end
    else
        --游戏已结束
    end
end


function event:peng(_, resp)
    if MainScene._self.tableview then
        MainScene._self.tableview:onpeng(resp)
    end
end

function event:onpeng(args)
    if MainScene._self.tableview then
        MainScene._self.tableview:onpeng(args)
    end
end

function event:waitpeng(args)
    if MainScene._self.tableview then
        MainScene._self.tableview:waitpeng(args)
    end
end

function event:hu(_, resp)
    -- MainScene._self:showGameResult(args)
end

function event:ongameover(args)
   MainScene._self:showGameResult(args)
end

function scnet.tcpConnected()
    MainScene._self.recv =0
    MainScene._self.heartbeat=0
    print("connect gate success!")
    scnet.connected = true
    socketMsg=""
    message.setSocket(scnet.socket)
    --shakehand
    local handshake = string.format("%s:%d",userid, index)
    message.request("handshake",{data=handshake .. ":" .. crypto.encodeBase64(handshake)})
    --message.request("ping")
end


local last = ""
local data = ""
local receiveIndex = 1
local receiveBuffer = ""
local msgHeaderLen = 0

function scnet.receive(event)
    MainScene._self.recv = MainScene._self.recv + 1
    receiveBuffer = receiveBuffer..event.data
    while true and #receiveBuffer>0 do
        if msgHeaderLen == 0 then
            if  #receiveBuffer<2 then
                return
            end
                local nextReceiveIndex, msgSize = string.unpack(receiveBuffer, '>H', receiveIndex);
                if  #receiveBuffer < 2+msgSize then
                return
            end
            -- print(nextReceiveIndex,msgSize,#receiveBuffer)
            -- print(#string.sub(receiveBuffer,nextReceiveIndex,nextReceiveIndex+msgSize-1))
            -- print("=========",receiveBuffer,nextReceiveIndex,nextReceiveIndex+msgSize-1)
            message.update(string.sub(receiveBuffer,nextReceiveIndex,nextReceiveIndex+msgSize-1))
            msgHeaderLen=0
            receiveIndex=1
            receiveBuffer=string.sub(receiveBuffer,nextReceiveIndex+msgSize) 
        end
    end
end

function MainScene:disconnectGate()

    if scnet.socket~= nil  and  scnet.connected then
        scnet.socket:close()
         scnet.socket = nil
    end
end

function MainScene:connectGate()

    scnet.socket = net.SocketTCP.new()
     scnet.socket:addEventListener(net.SocketTCP.EVENT_CLOSED, function()
         scnet.connected = false
         socketMsg=nil
    end)
    scnet.socket:addEventListener(net.SocketTCP.EVENT_CONNECT_FAILURE, function()
        scnet.connected = false
        socketMsg=nil
    end)
    scnet.socket:addEventListener(net.SocketTCP.EVENT_CONNECTED, scnet.tcpConnected)
    scnet.socket:addEventListener(net.SocketTCP.EVENT_DATA, scnet.receive)
    local ip,port = string.match(GAME_IP,"([^:]+):(.+)")
    scnet.socket:connect(ip,port)
end

 
local itemWidth = 200
local itemHeight= 80
local item

function MainScene:roomList(list)
    if list ~= nil and #list > 0 then
        local count = #list
        local side = 150
        local viewRect = cc.rect((display.width-600)/2, 40, 600, display.height-40*2)
        if  self.lvGrid == nil then
        self.lvGrid = cc.ui.UIListView.new {
        -- bgColor = cc.c4b(200, 200, 200, 120),
        -- bg = "sunset.png",
        viewRect = viewRect,
        direction = cc.ui.UIScrollView.DIRECTION_VERTICAL}
        :addTo(self)        
    end
        -- add items
     

        local num = 3
        local row = count/num
        if math.floor(count/num) ~= row then
            row = math.floor(count/num) +1
        end
        local index = 1
        for i=1,row do
             item = self.lvGrid:newItem()
            local content
            content = display.newNode()
            for column = 1, num do
                if index > count then
                    break
                end
               local room = list[index]
              local myRoom=  cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
                local  roomLabel = cc.ui.UILabel.new({text = room.name..":"..room.id, size = 16, color = display.COLOR_BLUE})
                myRoom:setButtonSize( itemWidth,itemHeight)
                :setButtonLabel(roomLabel)
                    :onButtonPressed(function(event)
                        event.target:getButtonLabel():setColor(display.COLOR_RED)
                    end)
                    :onButtonRelease(function(event)
                        event.target:getButtonLabel():setColor(display.COLOR_BLUE)
                    end)
                    :onButtonClicked(function(event)
                        self:roomClick(room)
                    end)
                   :align(display.CENTER, itemWidth*column-itemWidth/2,itemHeight/2)
                    :addTo(content)
                    :setTouchSwallowEnabled(false)
                index = index + 1
            end
            content:setContentSize(itemWidth*num, itemHeight)
            item:addContent(content)
            item:setMargin({left=0,top=10,right=10,bottom=10})
            item:setItemSize(itemWidth*num, itemHeight)
            self.lvGrid:addItem(item)
        end
        self.lvGrid:reload()
    end
end

function MainScene:addItem(room)
local column = 2
    -- if column == 3 then
    --     column =1 
    --     item = self.lvGrid:newItem()
    --  end
   local content = display.newNode()
   cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
                    :setButtonSize( itemWidth,itemHeight)
                    :setButtonLabel(cc.ui.UILabel.new({text = room.name, size = 16, color = display.COLOR_BLUE}))
                    :onButtonPressed(function(event)
                        event.target:getButtonLabel():setColor(display.COLOR_RED)
                    end)
                    :onButtonRelease(function(event)
                        event.target:getButtonLabel():setColor(display.COLOR_BLUE)
                    end)
                    :onButtonClicked(function(event)
                    end)
                   :align(display.CENTER, itemWidth*column-itemWidth/2,itemHeight/2)
                    :addTo(content)
                    :setTouchSwallowEnabled(false)
   content:setContentSize(itemWidth*3, itemHeight)
    item:addContent(content)
    if column == 1 then
        item:setMargin({left=0,top=10,right=10,bottom=10})
        item:setItemSize(itemWidth*3, itemHeight)
        self.lvGrid:addItem(item)
    end
   self.lvGrid:reload()

end

function event:createroom(_, resp)
    if resp.ok == 0 then 
        print("创建房间成功,名字为：",resp.room.name)
        -- if  self.lvGrid  == nil then
        --     event.scene:roomList({resp.room})
        -- else
            MainScene._self.createView:removeSelf()
            -- 
            if  MainScene._self.lvGrid ~= nil then
                 MainScene._self.lvGrid:removeAllItems()
                message.request("roomlist",{page=1})
            else
                MainScene._self:roomList({resp.room})
            end

            -- app:enterScene("GameScene", {socketData,{userid=userid}}, "fade", 0.6, display.COLOR_WHITE)

        MainScene._self.tableview=app:createView("TableView",socketData,{userid=userid,roomid=resp.room.id})
        :pos(0,0)
        :addTo(MainScene._self)
             --message.request("roomlist",{page=1})
              -- message.request("gameready")
        -- end
    else
        print("创建房间失败")
    end
end

function event:onroom(args)
    socketData.onroom(args)
end

function event:ongameready(args)
    socketData.ongameready(args)
end

function event:takecard(_,resp)
    socketData.takecard(resp)
end

function event:oncardnum(args)
    print("oncardnum",args.count)
    -- dump(args)
end 

function event:playcommand(_,resp)
    -- dump(resp)
    socketData.playcommand(resp)
end

function event:onaiplay(args)
    MainScene._self.tableview:onaiplay(args)
end

function event:onplay(args)
    socketData.onplay(args)
end

function event:roomcommand(_,resp)
    if resp.ok == 0 then
        MainScene._self.tableview=app:createView("TableView",socketData,{userid=userid,user=resp.user,roomid= MainScene._self.roomid})
        :pos(0,0)
        :addTo(MainScene._self)
        -- app:enterScene("GameScene", {socketData,{userid=userid,user = resp.user}}, "fade", 0.6, display.COLOR_WHITE)
    elseif  resp.ok == 1 then
        if MainScene._self.tableview then
            MainScene._self.tableview:destory()
            MainScene._self.tableview:removeSelf()
            MainScene._self.tableview = nil
        end
    end
end

function socketData.request(...)
    message.request(...)
end

function MainScene:roomClick(room)
     MainScene._self.roomid=room.id
     message.request("roomcommand",{id=room.id,cmd=0})
end

function MainScene:showGameResult(args)
    MainScene._self.resultView=app:createView("GameResultView",args)
    :pos(0,0)
    :addTo(MainScene._self)
    args.close = function()
     MainScene._self.tableview:removeSelf()
    end
end

function MainScene:showReConnectTip()
      device.showAlert("提示", "已掉线，确定重新连接吗 ?", {"确定", "取消"}, function(event)
    if event.buttonIndex == 1 then
            self:disconnectGate()
            self:connectGate()
       else
             if MainScene._self.tableview then
                MainScene._self.tableview:destory()
                MainScene._self.tableview:removeSelf()
                MainScene._self.tableview = nil
            end
            app:enterScene("LoginScene", {}, "fade", 0.6, display.COLOR_WHITE)
       end
    end)
end

return MainScene
